package com.trc202.MemoryManagers;
//Term Project Ted Chandler and Daniel Moore
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;

import com.trc202.CS350.Job;
import com.trc202.CS350.MemorySegment;

public class SJFirstServed extends MemoryManager{
	
	public SJFirstServed(Job[] jobs, MemorySegment[] memory) {
		super(jobs, memory);
	}
	
	@Override
	public void manageMemory() {
		super.manageMemory();
		ArrayList<Job> avalableJobs = getAvalableJobs();
		Collections.sort(avalableJobs); //Job Class is comparable, sorts Jobs based on size
		for(Job j : avalableJobs){
			Iterator<MemorySegment> freeRam = getFreeRam().iterator();
			MemorySegment closest = getClosestFit(freeRam, j.getRequiredRam());
			if(closest != null){
				j.setAssignedSegmentNum(closest.getSegmentNum());
				j.setStatus(Job.Status.READY);
				closest.setMBUsed(j.getRequiredRam());
			}
		}
	}
	
	/**
	 * Finds the closest available match to the given job size
	 * @param freeRam
	 * @param jobSize
	 * @return null if no match could be found
	 */
	public MemorySegment getClosestFit(Iterator<MemorySegment> freeRam, int jobSize){
		MemorySegment bestMatch = null;
		while(freeRam.hasNext()){
			MemorySegment current = freeRam.next();
			if(current.getSize() > jobSize){
				if(bestMatch != null && bestMatch.getSize() > current.getSize()){
					bestMatch = current;
				}else if(bestMatch == null){
					bestMatch = current;
				}else{
					//Do nothing, current is larger than the bestMatch
				}
			}
		}
		return bestMatch;
	}
}
